import React, { useState } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  Typography, 
  message,
  Space,
  Upload,
  Tabs,
  Row,
  Col,
  InputNumber
} from 'antd';
import { useNavigate } from 'react-router-dom';
import { UploadOutlined, CodeOutlined } from '@ant-design/icons';
import { createFunction } from '../../services/api';

const { Title } = Typography;
const { TextArea } = Input;
const { TabPane } = Tabs;

const FunctionCreate = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [codeContent, setCodeContent] = useState('');
  const [activeTab, setActiveTab] = useState('code');
  const navigate = useNavigate();

  const onFinish = async (values) => {
    try {
      setLoading(true);
      // Process environment variables
      let env = {};
      if (values.envVars) {
        values.envVars.split('\n').forEach(line => {
          const [key, value] = line.split('=');
          if (key && value) {
            env[key.trim()] = value.trim();
          }
        });
      }

      // Process resource limits
      const limits = {};
      if (values.memoryLimit) limits.memory = values.memoryLimit;
      if (values.cpuLimit) limits.cpu = values.cpuLimit;

      // Process resource requests
      const requests = {};
      if (values.memoryRequest) requests.memory = values.memoryRequest;
      if (values.cpuRequest) requests.cpu = values.cpuRequest;

      const functionData = {
        name: values.name,
        version: values.version,
        description: values.description,
        timeout: values.timeout,
        handler: values.handler,
        image: values.image,
        env,
        limits,
        requests,
        code: activeTab === 'code' ? codeContent : undefined
      };

      const response = await createFunction(functionData);
      message.success(response.data.message);
      navigate('/functions');
    } catch (error) {
      message.error('创建函数失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  return (
    <Card>
      <Title level={3}>创建函数</Title>
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        initialValues={{
          timeout: 30,
          version: 'v1.0.0',
          memoryLimit: '128Mi',
          cpuLimit: '100m',
          memoryRequest: '64Mi',
          cpuRequest: '50m'
        }}
      >
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="name"
              label="函数名称"
              rules={[{ required: true, message: '请输入函数名称!' }]}
            >
              <Input placeholder="例如: my-function" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="version"
              label="版本"
            >
              <Input placeholder="例如: v1.0.0" />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="description"
          label="函数描述"
        >
          <Input placeholder="请输入函数描述" />
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="timeout"
              label="执行时限(秒)"
            >
              <InputNumber min={1} max={300} style={{ width: '100%' }} placeholder="例如: 30" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="handler"
              label="Handler"
              rules={[{ required: true, message: '请输入Handler!' }]}
            >
              <Input placeholder="例如: index.handler" />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="image"
          label="Docker镜像"
          rules={[{ required: true, message: '请输入Docker镜像地址!' }]}
        >
          <Input placeholder="例如: docker.io/myuser/myfunction:latest" />
        </Form.Item>

        <Card size="small" title="资源配置" style={{ marginBottom: 20 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="memoryRequest"
                label="内存请求"
              >
                <Input placeholder="例如: 64Mi" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="memoryLimit"
                label="内存限制"
              >
                <Input placeholder="例如: 128Mi" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="cpuRequest"
                label="CPU请求"
              >
                <Input placeholder="例如: 50m" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="cpuLimit"
                label="CPU限制"
              >
                <Input placeholder="例如: 100m" />
              </Form.Item>
            </Col>
          </Row>
        </Card>

        <Form.Item
          name="envVars"
          label="环境变量 (key=value 每行一个)"
        >
          <TextArea 
            placeholder="例如:&#10;NODE_ENV=production&#10;LOG_LEVEL=info" 
            rows={4}
          />
        </Form.Item>

        <Card size="small" title="函数代码" style={{ marginBottom: 20 }}>
          <Tabs activeKey={activeTab} onChange={setActiveTab}>
            <TabPane tab={<span><CodeOutlined />在线编辑</span>} key="code">
              <Form.Item label="代码">
                <TextArea
                  value={codeContent}
                  onChange={(e) => setCodeContent(e.target.value)}
                  rows={10}
                  placeholder="在此输入您的函数代码"
                />
              </Form.Item>
            </TabPane>
            <TabPane tab={<span><UploadOutlined />上传文件</span>} key="upload">
              <Form.Item
                name="codeFile"
                valuePropName="fileList"
                getValueFromEvent={normFile}
              >
                <Upload.Dragger 
                  beforeUpload={() => false} 
                  maxCount={1}
                  accept=".zip,.tar.gz,.js,.py"
                >
                  <p className="ant-upload-drag-icon">
                    <UploadOutlined />
                  </p>
                  <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                  <p className="ant-upload-hint">支持.zip, .tar.gz, .js, .py等格式</p>
                </Upload.Dragger>
              </Form.Item>
            </TabPane>
          </Tabs>
        </Card>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              创建函数
            </Button>
            <Button htmlType="button" onClick={() => form.resetFields()}>
              重置
            </Button>
            <Button htmlType="button" onClick={() => navigate('/functions')}>
              取消
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default FunctionCreate;